package fina2.dcs.security;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.Remove;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;
import org.jboss.annotation.ejb.LocalBinding;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;

@Stateless
@Scope(ScopeType.SESSION)
@Name("roleSession")
@LocalBinding(jndiBinding = "RoleSession/local")
@AutoCreate
public class RoleSession implements RoleLocal, Serializable {
	@PersistenceContext
	private EntityManager em;

	
	private Logger log=Logger.getLogger(getClass());

	

	private List<String> perms = null;


	public List<String> loadPermissions(BigDecimal userId) {
		
		List<String> ps = new ArrayList<String>();
		String sql = "SELECT p.idName FROM " + Permission.class.getName() + " p WHERE p.id IN(SELECT r.rolePermPk.permissionId FROM " + RolePermission.class.getName() + " r WHERE r.rolePermPk.roleId IN(SELECT ur.userRolePk.roleId FROM " + UserRole.class.getName() + " ur WHERE ur.userRolePk.userId=:userId))";
		try {
			Query q = em.createQuery(sql);
			q.setParameter("userId", userId);
			ps = q.getResultList();

		} catch (Exception ex) {
			log.error(sql);
			log.error(ex.getMessage(), ex);
		}
		
		return ps;
	}

	@Remove
	public void remove() {
		if (perms != null) {
			perms.clear();
			perms = null;
		}
	}

}
